/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.edu.kamai.media.audio;

import javax.sound.sampled.UnsupportedAudioFileException;

/**
 *
 * @author xzhu
 */
public class AudioPlayer {
    
    public AudioPlayer(){
        
    }
    
    public AudioPlayer(String fn){
        fileName = fn;
    }
    
    private void playMP3(String fn){
        System.out.println("in mp3 function");
        try{
            wav = null;
            mp3 = new mp3Player(fn);
            mp3.play();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
    
    private void playWMA(String fn){
        System.out.println("in wma function");
        try{
            mp3 = null;
            wav = new wavPlayer(fn);
            try{
                wav.init();
            }catch(UnsupportedAudioFileException ex){
                playMP3(fn);
            }
            if(wav != null){
                wav.start();
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
    
    public int play(){
        if(fileName != null){
            int pos = fileName.lastIndexOf(".");
            String ext = fileName.substring(pos + 1);
            if(ext.equalsIgnoreCase("mp3")){
                playMP3(fileName);
            }else if(ext.equalsIgnoreCase("wma")){
                playWMA(fileName);
            }else {
                return -1;
            }
        }
        return 1;
    }
        
    public void stop(){
        if(mp3 != null){
            mp3.close();
        }else if(wav != null){
            wav.close();
        }
    }
    
    public boolean isComplete(){
        if(mp3 != null){
            return mp3.isFinished();
        }else if(wav != null){
            return wav.isFinished();
        }
        return false;
    }
    
    
    private mp3Player mp3;
    private wavPlayer wav;
    private String fileName;
    
    
    public static void main(String[] args){
        String filename = "D:\\19\\s\\speaking_beep2.mp3";
        filename = "F:\\music\\03 曲目 3.wma";
        filename = "D:\\19\\s\\Speaking Q2_instruction.mp3";
        AudioPlayer ta = new AudioPlayer(filename);
        ta.play();
        try{
            while(ta.isComplete() == false){
                System.out.println("not finished");
                Thread.sleep(500);
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        System.out.println("finished");
    }
            
}
